<template>
    <el-form ref="formRef" label-width="85px" :model="formData" :disabled="pageType == 'look'">
        <el-form-item label="签到类型">
            <el-radio-group v-model="formData.sign_type">
                <el-radio :label="1">连续签到</el-radio>
                <el-radio :label="2">累计签到</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="添加奖项">
            <div class="award">
                <div class="top_btn">
                    <el-button plain size="small" @click="addTab">添加奖项</el-button>
                </div>
                <el-tabs
                    v-model="nameIndex"
                    type="card"
                    class="demo_tabs"
                    :closable="pageType !== 'look'"
                    @tab-remove="removeTab">
                    <el-tab-pane
                        v-for="(item, index) in formData.sign_config"
                        :key="`sign_config.${index}.stage_name`"
                        :label="`奖项${index + 1}`"
                        :name="`${index + ''}`">
                        <el-form-item
                            key="stage_name"
                            label="阶段名"
                            :prop="`sign_config.${index}.stage_name`"
                            :rules="formRules.stage_name"
                            style="width: 460px; margin-bottom: 20px">
                            <el-input
                                v-model="item.stage_name"
                                class="stage_name_inp"
                                placeholder="请输入阶段名"
                                maxlength="15"
                                show-word-limit
                                :clearable="true"></el-input>
                        </el-form-item>
                        <!-- :min="formData.sign_config[index - 1] ? formData.sign_config[index - 1].sign_days + 1 : 0"
                :max="formData.sign_config[index + 1] ? formData.sign_config[index + 1].sign_days - 1 : 10000" -->
                        <el-form-item
                            :key="`sign_days${index}`"
                            :label="formData.sign_type == 1 ? '连续签到' : '累计签到'"
                            :prop="`sign_config.${index}.sign_days`"
                            :rules="formRules.sign_days"
                            style="width: 500px; margin-bottom: 20px">
                            <el-input-number
                                v-model="item.sign_days"
                                :min="0"
                                style="width: 340px"
                                :controls="false"
                                :precision="0"
                                placeholder="请输入签到天数"
                                @blur="onSignDays(index)" />
                            天
                        </el-form-item>
                        <el-form-item label="奖品类型" style="width: 300px; margin-bottom: 20px">
                            <el-radio-group v-model="item.prize_type" @change="() => handleRewardTypeChange(item)">
                                <el-radio :label="1">实物</el-radio>
                                <el-radio v-if="!state.infoData.merchant_sn_disabled" :label="2">红包</el-radio>
                                <el-popover
                                    v-if="state.infoData.merchant_sn_disabled"
                                    placement="top"
                                    trigger="hover"
                                    :width="150">
                                    <div class="weiworkpaytip">请先配置企微支付</div>
                                    <template #reference>
                                        <el-radio :label="2" :disabled="state.infoData.merchant_sn_disabled"
                                            >红包</el-radio
                                        >
                                    </template>
                                </el-popover>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item>
                            <div class="prize_type">
                                <template v-if="item.prize_type == 2">
                                    <el-form-item label="红包类型">
                                        <el-radio-group
                                            v-model="item.red_bao.red_envelope_type"
                                            @change="handleRedEnvelopeTypeChange(item)">
                                            <el-radio :label="1">普通红包</el-radio>
                                            <el-radio :label="2">拼手气红包</el-radio>
                                        </el-radio-group>
                                    </el-form-item>
                                    <el-form-item
                                        :key="`sign_days${index}`"
                                        label="红包个数"
                                        :prop="`sign_config.${index}.red_bao.red_envelope_num`"
                                        :rules="formRules.red_bao.red_envelope_num">
                                        <el-input-number
                                            v-model="item.red_bao.red_envelope_num"
                                            :min="1"
                                            :controls="false"
                                            :precision="0"
                                            placeholder="请输入红包个数" />
                                        <span class="unit">个</span>
                                    </el-form-item>
                                    <el-form-item
                                        :key="`sign_days${index}`"
                                        label="单个红包金额"
                                        :prop="`sign_config.${index}.red_bao.red_envelope_money`"
                                        :rules="formRules.red_bao.red_envelope_money"
                                        :class="{ random_envelope: item.red_envelope_type === 2 }">
                                        <el-input-number
                                            v-model="item.red_bao.red_envelope_money"
                                            style="width: 100px"
                                            :min="0.3"
                                            :max="200"
                                            :controls="false"
                                            :precision="2"
                                            placeholder="请输入红包金额" />
                                        <span class="unit">元</span>
                                        <span v-if="item.red_bao.red_envelope_type === 2" class="random_envelope_range">
                                            <span style="margin: 10px">-</span>
                                            <el-input-number
                                                v-model="item.red_bao.red_envelope_range"
                                                style="width: 100px"
                                                :min="0.3"
                                                :max="200"
                                                :controls="false"
                                                :precision="2"
                                                placeholder="请输入红包金额" />
                                            <span class="unit">元</span>
                                        </span>
                                    </el-form-item>
                                    <el-form-item label="红包总金额">
                                        <span style="color: #ff6b00">{{ handleRedEnvelopeTotal(item) }}</span>
                                    </el-form-item>
                                    <div class="money_rule">
                                        <p>
                                            使用红包之前请先前往【微信支付商户平台-商户平台-产品中心-付款到零钱-产品设置】中完成以下配置
                                        </p>
                                        <p>1、【同一用户单日收款次数】调整为10次</p>
                                        <p>2、【单日付款总数】调整为100000元</p>
                                        <p>3、【同一用户收款额度】上限调整至200元</p>
                                    </div>
                                </template>
                                <template v-else>
                                    <el-form-item
                                        :key="`prize_title${index}`"
                                        label="奖品标题"
                                        :prop="`sign_config.${index}.entity.prize_title`"
                                        :rules="formRules.prize_title"
                                        style="width: 460px; margin-bottom: 20px">
                                        <el-input
                                            v-model="item.entity.prize_title"
                                            class="stage_name_inp"
                                            placeholder="请输入奖品标题"
                                            maxlength="15"
                                            show-word-limit
                                            :clearable="true">
                                        </el-input>
                                    </el-form-item>
                                    <el-form-item
                                        :key="`prize_url${index}`"
                                        label="奖品图片"
                                        :prop="`sign_config.${index}.entity.prize_url`"
                                        :rules="formRules.prize_url">
                                        <UploadImg
                                            :rule="{
                                                type: 'jpg|JPG|jpeg|JPEG|png|PNG',
                                                unit: 'MB',
                                                size: 2
                                            }"
                                            :url="item.entity.prize_url"
                                            @submit="v => (item.entity.prize_url = v)" />
                                        <div class="text">
                                            图片支持JPG、PNG、JPEG格式，大小2M以内，建议宽高比为1：1，尺寸200px*200px。
                                        </div>
                                    </el-form-item>
                                </template>
                                <el-form-item label="阶段客户打标" class="is_open_stage_tag">
                                    <el-switch v-model="item.is_open_stage_tag" :active-value="1" :inactive-value="2" />
                                </el-form-item>
                                <el-form-item
                                    v-if="item.is_open_stage_tag == 1"
                                    :key="`stage_cust_tags${index}`"
                                    label=" "
                                    :prop="`sign_config.${index}.stage_cust_tags`"
                                    :rules="formRules.stage_cust_tags"
                                    class="reward-item">
                                    <div>
                                        <el-tag
                                            v-for="tag in AllTags[nameIndex]"
                                            :key="tag"
                                            class="mx-1"
                                            size="small"
                                            style="margin-right: 5px"
                                            :closable="pageType !== 'look'"
                                            @close="onClose1(tag)">
                                            {{ tag.name }}
                                        </el-tag>
                                    </div>
                                    <el-button @click="selecTag">选择标签</el-button>
                                </el-form-item>
                            </div>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-form-item>
        <el-form-item label="兑奖客服" :prop="`exchange_kf`" :rules="formRules.exchange_kf">
            <div class="form-staffs">
                <div class="staffs">
                    <el-tag
                        v-for="item in employeeList"
                        :key="item.name"
                        class="staffs_item"
                        :closable="pageType !== 'look'"
                        :type="item.id"
                        @close="handleClose(item)">
                        {{ item.name }}
                    </el-tag>
                </div>
            </div>
            <el-button class="select-staffs" @click="openDepart">选择员工</el-button>
        </el-form-item>
    </el-form>
    <ZWDepart ref="DepartRef" :type="1" @submit="getDepart" />
    <BatchLabel ref="BatchLabelRef" :title-visible="false" @save="getTags" />
</template>

<script setup lang="ts">
import UploadImg from '@/view/smartMarketing/components/UploadImg.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import { ref, defineExpose, defineProps, watch, reactive, onMounted } from 'vue';
import BatchLabel from '@/view/customer/groupManage/components/BatchLabel.vue';
import { getBusinesspay } from '@/api/channelconfig/enterprisepayment';
import { Picture as IconPicture, Plus } from '@element-plus/icons-vue';
import { getSetionId, IsNotEmpty } from '@/utils/utils';
import { ElMessage } from 'element-plus';
interface Props {
    pageType: any;
}
const props = withDefaults(defineProps<Props>(), {
    pageType: ''
});
const emit = defineEmits(['submit', 'toData']);
const BatchLabelRef: any = ref(null);
const DepartRef: any = ref<any>(null); // 部门弹框类型
const searchSelectRef: any = ref<any>(null); // 部门弹框类型
const formRef = ref<any>(null);
const formData = ref({
    sign_type: 1,
    sign_config: [
        {
            stage_name: '', //阶段名称
            sign_days: void 0, //天数
            prize_type: 1, //奖品类型，1：实物 2：红包
            entity: {
                prize_title: '', //奖品名称
                prize_url: '' //奖品图片
            }, //实物配置
            red_bao: {
                red_envelope_type: 1, //红包类型，1：普通红包 2：拼手气红包
                red_envelope_money: 0, //普通红包单个红包金额
                red_envelope_range: 200, //普通红包单个红包金额下一个值的范围
                red_envelope_num: 0, //普通红包红包个数
                red_envelope_total: 0, //普通红包红包总金额
                red_envelope_range_total: 0 //单个红包范围（拼手气红包右）
            }, //红包配置
            is_open_stage_tag: 1, //是否开启阶段标签
            stage_cust_tags: []
        }
    ], //签到设置
    exchange_kf: [] //兑奖客服
});
const formRefList = ref([]);
const onFormRef = (el: any) => {
    if (el) {
        formRefList.value.push(el);
    }
};
const signDaysValidator = (rule: any, value: any, callback: any) => {
    if (value) {
        callback();
    } else {
        callback(new Error('请输入签到天数'));
    }
};

const formRules = {
    sign_type: [{ required: true, message: '请选择签到类型', trigger: 'blur' }],
    sign_config: [{ required: true, message: '请添加奖项', trigger: 'blur' }],
    prize_type: [{ required: true, message: '请选择奖品类型', trigger: 'blur' }],
    prize_title: [{ required: true, message: '请输入奖品标题', trigger: 'blur' }],
    prize_url: [{ required: true, message: '请选择奖品图片', trigger: 'change' }],
    red_bao: {
        amount: [{ required: true, message: '请输入红包金额', trigger: 'blur' }],
        red_envelope_money: [{ required: true, message: '请输入单个红包金额', trigger: 'blur' }],
        red_envelope_range: [{ required: true, message: '请输入单个红包金额', trigger: 'blur' }],
        red_envelope_num: [{ required: true, message: '请输入红包个数', trigger: 'blur' }],
        red_envelope_total: [{ required: true, message: '请输入红包总金额', trigger: 'blur' }],
        red_envelope_type: [{ required: true, message: '请选择红包类型', trigger: 'blur' }]
    },
    stage_name: [{ required: true, message: '请输入阶段名称', trigger: 'blur' }],
    stage_cust_tags: [{ required: true, message: '请选择标签', trigger: 'change' }],
    sign_days: [
        { required: true, message: '请输入签到天数', trigger: 'blur' },
        { validator: signDaysValidator, trigger: 'blur' }
    ],
    exchange_kf: [{ required: true, message: '请选择兑奖客服', trigger: 'change' }]
};
const nameIndex = ref('0');
const AllTags = ref([[]]);
const employeeList = ref([]);
const addTab = () => {
    formData.value.sign_config.push({
        stage_name: '', //阶段名称
        sign_days: void 0, //天数
        prize_type: 1, //奖品类型，1：实物 2：红包
        entity: {
            prize_title: '', //奖品名称
            prize_url: '' //奖品图片
        }, //实物配置
        red_bao: {
            red_envelope_type: 1, //红包类型，1：普通红包 2：拼手气红包
            red_envelope_money: 0, //普通红包单个红包金额
            red_envelope_range: 200, //普通红包单个红包金额下一个值的范围
            red_envelope_num: 0, //普通红包红包个数
            red_envelope_total: 0, //普通红包红包总金额
            red_envelope_range_total: 0 //单个红包范围（拼手气红包右）
        }, //红包配置
        is_open_stage_tag: 1, //是否开启阶段标签
        stage_cust_tags: [] //阶梯客户标签
    });
    AllTags.value.push([]);
    nameIndex.value = (formData.value.sign_config.length - 1).toString();
};
const onSignDays = (index: number) => {
    if (formData.value.sign_config[index + 1]) {
        if (formData.value.sign_config[index].sign_days >= formData.value.sign_config[index + 1].sign_days) {
            ElMessage.warning('签到天数必须小于后一奖项');
            formData.value.sign_config[index].sign_days = 0;
        }
    }
    if (index > 0 && index + 1 <= formData.value.sign_config.length) {
        if (formData.value.sign_config[index].sign_days <= formData.value.sign_config[index - 1].sign_days) {
            ElMessage.warning('签到天数必须大于前一奖项');
            formData.value.sign_config[index].sign_days = 0;
        }
    }
};
const removeTab = (targetName: string) => {
    if (formData.value.sign_config.length > 1) {
        formData.value.sign_config.splice(targetName, 1);
        nameIndex.value = (formData.value.sign_config.length - 1).toString();
    }
};
// 红包类型改变
const handleRedEnvelopeTypeChange = (item: any) => {
    const { red_envelope_money: money = 0, red_envelope_range: range = 0, red_envelope_type } = item.red_bao;
    if (item.red_bao.red_envelope_type === 2) {
        if (money > range) {
            item.red_bao.red_envelope_range = money;
        } else {
            item.red_bao.red_envelope_range = +range || 200; // 默认拼手气红包最大值
        }
    }
};
// 计算红包总金额
let flag = props.pageType ? 0 : 1;
const computedAmount = (num: number, money: number) => ((num * money * 100) / 100).toFixed(2);
const handleRedEnvelopeTotal = (item: any) => {
    const {
        red_envelope_num: num = 0,
        red_envelope_money: money = 0,
        red_envelope_range: range = 0,
        red_envelope_type
    } = item.red_bao;

    const total = computedAmount(num, money);
    if (item.red_bao.red_envelope_type === 1) {
        // 普通红包
        item.red_bao.red_envelope_total = total;
        return `${total}元`;
    } else {
        const rangeTotal = computedAmount(num, range);
        if (money > range && flag > 0) {
            item.red_bao.red_envelope_money = 0.3;
        } else {
            flag++;
        }
        // 拼手气红包
        item.red_bao.red_envelope_total = total;
        // item.red_bao.red_envelope_range_total = rangeTotal
        return `${total}元~${rangeTotal}元`;
    }
};

// 打开选择标签弹框
const selecTag = () => {
    BatchLabelRef.value.dialogData.labelChooseType = 2;
    BatchLabelRef.value.chooseDataArr = [];
    BatchLabelRef.value.chooseDataArr = [...AllTags.value[nameIndex.value]];
    BatchLabelRef.value.dialogVisible = true;
};
// 获取标签1
const getTags = (data: any) => {
    AllTags.value[nameIndex.value] = data.data;
    formData.value.sign_config[nameIndex.value].stage_cust_tags = getSetionId('id', data.data);
};
// 移除标签
const onClose1 = (tag: any) => {
    AllTags.value[nameIndex.value] = AllTags.value[nameIndex.value].filter(item => item.id != tag.id);
    formData.value.sign_config.stage_cust_tags = getSetionId('id', AllTags.value[nameIndex.value]);
};
//打开新建选择人
const openDepart = () => {
    DepartRef.value.isQRAuth = true;
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = [...employeeList.value];
};
// 获取部门成员
const getDepart = (res: any) => {
    employeeList.value = res;
    formData.value.exchange_kf = getSetionId('id', employeeList.value);
};
// 员工移除
const handleClose = (tag: any) => {
    employeeList.value = employeeList.value.filter((item: any) => item.id !== tag.id);
    formData.value.exchange_kf = getSetionId('id', employeeList.value);
    DepartRef.value.removeItem(tag);
};
const state = reactive({
    infoData: {
        merchant_sn: '',
        merchant_sn_disabled: false
    }
});
const onload = async () => {
    state.infoData = await getBusinesspay({});

    if (state.infoData.merchant_sn == '') {
        state.infoData.merchant_sn_disabled = true;
    }
};
onMounted(() => {
    onload();
});

const onSubmit = async () => {
    if (!formRef.value) return;
    formRef.value!.validate((valid: any, fields: any) => {
        let sum = 0;
        for (const rewardItem of formData.value.sign_config) {
            if (rewardItem.prize_type !== 2) continue;

            if (rewardItem.red_bao.red_envelope_type === 1) {
                sum += rewardItem.red_bao.red_envelope_money * rewardItem.red_bao.red_envelope_num;
            } else {
                sum += rewardItem.red_bao.red_envelope_num * rewardItem.red_bao.red_envelope_range;
            }
        }
        if (sum > 100000) {
            ElMessage.error('红包总金额不得超过10万元');
            return;
        }
        if (valid) {
            emit('submit');
        } else {
            const num = +Object.keys(fields)[0][12] + 1;
            const message = num ? `奖项${num}：${Object.values(fields)[0][0].message}` : '请选择兑奖客服';
            ElMessage.warning(message);
        }
    });
};
watch(
    formData,
    val => {
        emit('toData', val);
    },
    { deep: true }
);

defineExpose({
    formData,
    onSubmit,
    formRefList,
    employeeList,
    AllTags
});
const handleRewardTypeChange = (item: any) => {
    if (item.prize_type === 2) {
        item.red_bao.red_envelope_type = item.red_bao.red_envelope_type || 1;
    }
};
</script>

<style lang="scss" scoped>
.stage_name_inp {
    :deep(.el-input__suffix) {
        .el-input__validateIcon {
            display: none;
        }
    }
}

.el-form-item .el-form-item {
    margin-bottom: 20px;
}

.unit {
    margin-left: 10px;
}

:deep .el-input__inner::-webkit-outer-spin-button,
:deep .el-input__inner::-webkit-inner-spin-button {
    appearance: none !important;
    margin: 0;
}

.hide :deep .el-upload--picture-card {
    display: none;
}

:deep .el-tabs--card > .el-tabs__header .el-tabs__item.is-active.is-closable {
    border-bottom: 2px solid #ff6b00;
}

:deep .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border: none;
}

:deep .el-tabs__nav-scroll {
    width: 85%;
}

:deep .el-tabs__nav-next {
    right: 105px;
}

.money_rule {
    // width: 576px;
    // height: 98px;
    background: #fffaf9;
    margin-bottom: 10px;
    font-size: 12px;
    color: #ff6b00;
    line-height: 20px;
    padding: 16px;
}

.award {
    position: relative;

    // height: 550px;
    padding-top: 20px;
    background: #fff;
    border-radius: 4px;

    // border: 1px solid #eaeaea;
    .top_btn {
        position: absolute;
        right: 12px;
        top: 24px;
        z-index: 10;
    }

    .demo_tabs {
        border: 1px solid #eaeaea;

        .prize_type {
            width: 500px;
            padding: 20px 0 18px 20px;
            margin-bottom: 20px;
            margin-left: 100px;
            border: 1px solid #eaeaea;

            :deep(.el-form-item) {
                .el-form-item__label {
                    width: 120px !important;
                }
            }
        }
    }
}

.el-form-item {
    margin-bottom: 24px;

    .text {
        padding-top: 10px;
        line-height: 1.4;
        font-size: 12px;
        color: #999;
    }
}

.is_open_stage_tag {
    margin-top: -15px;
    margin-bottom: 0 !important;
}

.reward-item {
    :deep(.el-form-item__label)::before {
        content: '' !important;
    }
}

.form-staffs {
    display: flex;

    .title {
        margin-right: 12px;
    }

    .staffs {
        &_item {
            height: 22px;
            line-height: 22px;
            margin-right: 6px;

            // padding: 0;
            color: #35383a;
            border: 1px solid #fffaf9;
            border-radius: 1px;
            background: #fffaf9;
        }

        :deep .el-tag .el-icon {
            width: 12px;
            height: 12px;
            color: #fff;
            background: #d9d9d9;
        }

        :deep .el-tag .el-icon svg {
            margin: 0;
        }

        :deep .el-tag .el-tag__close:hover {
            background: #d9d9d9;
        }

        :deep span.el-tag.el-tag--light.staffs_item::before {
            content: '';
            display: inline-block;
            width: 10px;
            height: 11px;
            background: url('@/assets/image/LiveCode/people_icon.png') center/100% no-repeat;
            margin-right: 10px;
        }
    }
}

.weiworkpaytip {
    text-align: center;
}
</style>
